<?php
namespace app\common\model;

use app\common\service\LangMap;
use think\model\concern\SoftDelete;

class UserLogsModel extends BaseModel
{
    use SoftDelete;
    protected $table = 'users_logs';

    protected $json = ['info','customer_money_info'];


    public static $fields_type = [
        ['name'=>'系统','value'=>0,'more'=>[
            ['name'=>'消费'],
        ]],
        ['name'=>'积分','value'=>1,'more'=>[
            0=>['name'=>'积分'],
            1=>['name'=>'签到'],
            2=>['name'=>'积分兑换'],
        ]],
        ['name'=>'余额','value'=>2,'more'=>[
            0=>['name'=>'余额'],
            1=>['name'=>'收入'],
            2=>['name'=>'订单消费'],
            3=>['name'=>'订单退款'],

            8=>['name'=>'用户充值',"params"=>[
                "customer_mch_id"=>[ 'name'=>'消费店铺', 'field'=>true, ],
                "customer_type"=>[ 'name'=>'消费类型', 'field'=>true,'type_class'=>OrderModel::class,'type_class_fields'=>'fields_type' ],
                "customer_no"=>[ 'name'=>'消费单号', 'field'=>true, ],
                "customer_card_no"=>[ 'name'=>'使用卡号', 'field'=>true, ],
                "customer_user_id"=>[ 'name'=>'消费用户', 'field'=>true, ],
                "customer_money"=>[ 'name'=>'消费金额', 'field'=>true, ],
                "customer_money_info"=>[ 'name'=>'比例信息', 'field'=>true,'field_format'=>[
                    ['name'=>'类型','field'=>'name'],
                    ['name'=>'比例','field'=>'per'],
                    ['name'=>'总金额','field'=>'money'],
                    ['name'=>'佣金','field'=>'commission_money'],
                    ['name'=>'获得金额','field'=>'get_money'],
                ] ],
            ]],
        ]],
    ];



    //获取佣金
    public static function getCommission($user_id,$style="today")
    {
        $where = [];
        $where[] = ['uid','=',$user_id];
        $where[] = ['type','=',2];
        if(empty($user_id)){
            return '0.00';
        }
        $where[] = ['type','=',2];
        $where[] = ['m_type','=',3];
        if($style=='today'){
            $time = strtotime(date('Y-m-d'));
            $where[] = ['create_time','>',$time];
        }elseif($style=='yesterday'){
            $time = strtotime(date('Y-m-d'));
            $where[] = ['create_time','>',strtotime('-1 day',$time)];
            $where[] = ['create_time','<',$time];
        }
        return self::where($where)->sum('money');
    }


    public static function getTotalMoney(array $input_data=[])
    {
        if(empty($input_data['uid'])){
            return '0.00';
        }
        return self::getPageData($input_data,'total_money');
    }

    /**
     *
     * @param array $input_data 请求内容
     * @param int|null $limit 页面条数
     * @throws
     * @return  \think\Paginator|Float
     * */
    public static function getPageData(array $input_data=[],$check_mode="")
    {
        $activeState = $input_data['activeState']??'';
        $search_month = $input_data['search_month']??'';
        $start_date = $input_data['start_date']??$search_month;
        $start_time = empty($start_date)? '' : strtotime($start_date);
        $end_date = $input_data['end_date']??'';
        $end_time = empty($end_date) ? '' : strtotime('+1 month',strtotime($end_date));
        $keyword = trim($input_data['keyword']??'');
        $where = [];
        !empty($keyword) && $where[] = ['uid','like','%'.$keyword.'%'];

        $limit = $input_data['limit']??null;

        if(isset($input_data['uid'])){
            $where[] = [ 'uid' , '=' , $input_data['uid'] ];
        }

        if(isset($input_data['type'])){
            $where[] = ['type','=',$input_data['type']];
        }

        if($activeState=='income'){
            $where[] = ['type','=',2];
            $where[] = ['m_type','=',1];
        }elseif($activeState=='consume'){//消费
            $where[] = ['type','=',2];
            $where[] = ['m_type','in',[2,3]];
        }elseif($activeState=='expense'){//消费
            $where[] = ['type','=',2];
            $where[] = ['m_type','in',[2,3]];
        }

        if(isset($input_data['check_mode'])){//--后台查询
            if($input_data['check_mode']=='money'){
                $where[] = ['type','=',2];
            }elseif($input_data['check_mode']=='integral'){
                $where[] = ['type','=',1];
            }
        }elseif($start_time && $end_time){
            $where[] = ['create_time','>',$start_time];
            $where[] = ['create_time','<=',$end_time];
        }elseif($start_time){
            $where[] = ['create_time','>',$start_time];
        }elseif($end_time){
            $where[] = ['create_time','<=',$end_time];
        }

        //总收益
        if($check_mode=='total_money'){
            return self::where($where)->sum('money');
        }else{
            $model = self::with(['linkCustomerUser',])->where($where)->order('id desc')->paginate($limit);

            return $model;
        }
    }




    /**
     * 记录日志
     * @param $type int 类型
     * @param $uid int 用户id
     * @param float $money 金额
     * @param string $intro 说明
     * @param array $info  扩展数据
     * */
    public static function recordData($type,$uid,$money,$intro,array $info=[])
    {
        $q_money = $info['q_money']??0;//变动前
        $h_money = $info['h_money']??0;//变动后
        $m_type = $info['m_type']??0;//更多
        $is_hide = $info['is_hide']??0;//是否隐藏
        unset($info['m_type'],$info['master_id'],$info['q_money'],$info['h_money'],$info['m_type'],$info['is_hide']);
        $model = new self();
        $model->setAttrs([
            'uid'=>$uid,
            'type'=>$type,
            'is_hide'=>$is_hide,
            'm_type'=>$m_type,
            'q_money'=>$q_money,
            'money'=>$money,
            'h_money'=>$h_money,
            'intro'=>$intro,
        ]);
        //增加额外字段信息
        $model->addExtraField($info);
        //扩展数据
        if(!empty($info)) $model->setAttr('info',json_encode($info));
        $model->save();
    }

    public function getCustomerMoneyInfoAttr($value)
    {
        $value = is_array($value) ? $value : json_decode($value,true);
        $type = $this->getAttr('type');
        $m_type = $this->getAttr('m_type');
        $type_info = self::getPropInfo('fields_type',$type,'more');
        $info_arr = $type_info[$m_type]??[];
        $data = [];

        if(!empty($info_arr) && is_array($value)){
            $handle_params = $info_arr['params']??[];
            $customer_money_info = $handle_params['customer_money_info']??[];
            $customer_format_data = $customer_money_info['field_format']??[];
            if(!empty($customer_format_data)){
                foreach ($value as $key=>$val){
                    $extra = [];
                    foreach ($customer_format_data as $info){
                        $format_name = $info['name'];
                        $format_field = $info['field'];
                        $extra[$format_field.'_name']=$format_name;
                        $extra['field']=$format_field;
                        $format_value = $val[$format_field]??'';
                        if($format_field=='ident_type'){
                            $ident_type_name = UserModel::getPropInfo('fields_type',0,'name');

                            $extra[$format_field.'_value'] = $ident_type_name;
                        }else{
                            $extra[$format_field.'_value']=$val[$format_field]??'';
                        }
                    }
                    array_push($data,$extra);
                }
            }
        }
        return $data;
    }

    //填充扩展信息
    public function addExtraField(array &$input_data = [])
    {
        $type = $this->getAttr('type');
        $m_type = $this->getAttr('m_type');
        $type_info = self::getPropInfo('fields_type',$type,'more');
        $info_arr = $type_info[$m_type]??[];
        if(!empty($info_arr)){
            $handle_params = $info_arr['params']??[];
            if(!empty($handle_params)){
                foreach ($handle_params as $table_field=>$vo){
                    //数据库字段
                    $table_field_state = empty($vo['field']) ? false : true;
                    //字段说明
                    $log_name = empty($vo['name']) ? '' : $vo['name'];
                    //分佣说明字段
                    $field_format = empty($vo['field_format']) ? [] : $vo['field_format'];
                    if($table_field_state){
                        if(isset($input_data[$table_field])){
                            $table_field_value =  $input_data[$table_field];
                            //注销改值；
                            unset($input_data[$table_field]);

                            if(empty($field_format)){
                                $this->setAttr($table_field, $table_field_value);
                            }elseif(is_array($table_field_value)){
                                $field_format_value = [];
                                foreach ($table_field_value as $item){
                                    $need_info = [];
                                    foreach ($field_format as $need_item){
                                        $need_data_name = $need_item['name'];
                                        $need_data_field = $need_item['field'];
                                        $need_info[$need_data_field] = $item[$need_data_field]??'';
                                    }
                                    array_push($field_format_value, $need_info);
                                }
                                if(!empty($field_format_value)){
                                    $this->setAttr($table_field, $field_format_value);
                                }
                            }
                        }
                    }

                }
            }
        }
    }

    public function apiFullInfo()
    {
        return array_merge($this->apiNormalInfo(),[

        ]);
    }

    public function apiNormalInfo()
    {
        return array_merge($this->apiExtraInfo(),[
            'id'=>$this['id'],
            'intro'=>$this['intro'],
            'q_money'=>$this['q_money'],
            'money'=>$this['money'],
            'h_money'=>$this['h_money'],
            'month_day' => substr($this['create_time'],5,5),
            'hour' => substr($this['create_time'],11,5),
            'date'=>substr($this['create_time'],0,10),
            'create_time'=>$this['create_time']
        ]);
    }


    public function linkUser()
    {
        return $this->belongsTo(UserModel::class,'uid');
    }

    public function apiExtraInfo()
    {
        $linkCustomerMaster = $this->getRelation('linkCustomerMaster');
        $linkCustomerMerchant = $this->getRelation('linkCustomerMerchant');
        $linkCustomerUser = $this->getRelation('linkCustomerUser');
        $type = $this->getAttr('type');
        $m_type = $this->getAttr('m_type');
        $type_info = self::getPropInfo('fields_type',$type,'more');
        $info_arr = $type_info[$m_type]??[];
        $return_data = [];
        if(!empty($info_arr)) {
            $handle_params = $info_arr['params'] ?? [];

            foreach ($handle_params as $table_field=>$vo){
                if($table_field=='customer_mch_id'){
                    $return_data['customer_mch_id'] =  empty($linkCustomerMerchant)?'':$linkCustomerMerchant['id'];
                    $return_data['customer_mch_name'] =  empty($linkCustomerMerchant)?'':$linkCustomerMerchant['name'];
                }elseif($table_field=='customer_master_id'){
                    $return_data['customer_master_id'] =  empty($linkCustomerMaster)?'':$linkCustomerMaster['id'];
                    $return_data['customer_master_name'] =  empty($linkCustomerMaster)?'':$linkCustomerMaster['name'];
                }elseif($table_field=='customer_user_id'){
                    $return_data['customer_user_id'] =  empty($linkCustomerUser)?'':$linkCustomerUser['id'];
                    $return_data['customer_user_name'] =  empty($linkCustomerUser)?'':$linkCustomerUser['name'];
                }elseif($table_field=='customer_type'){
                    $type_index = $this[$table_field];
                    $return_data['customer_type'] =  $this[$table_field];
                    $return_data['customer_type_name'] = $info_arr['name']??'';
                    if(isset($vo['type_class'])){
                        $class = $vo['type_class'];
                        $class_field = $vo['type_class_fields']??'';
                        if(!empty($class) && !empty($class_field)){
                            $return_data['customer_type_name'] = $class::getPropInfo($class_field, $type_index, 'name');
                        }
                    }
                }else{
                    $return_data[$table_field] = $this[$table_field];
                }
            }
        }


        return $return_data;
    }




    public function linkCustomerUser()
    {
        return $this->belongsTo(UserModel::class,'customer_user_id');
    }

}